package com.dimeng;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.dimeng.adapter.InfoAdapter;
import com.dimeng.entity.Info;
import com.dimeng.utils.AppCache;
import com.dimeng.utils.CommonUtil;
import com.dimeng.utils.Constant;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * @author write by ccn<br>
 * <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-4-27<br>
 * descrition:资讯视图
 */

public class InfoActivity extends SuperActivity {
	private static final long serialVersionUID = 2260882740898753026L;
	private final String INFO_CAT_ID = "infoCatId";
	private final String INFO_CAT_NAME = "infoCatName";
	private final String HOT_INFO_ACTION = Constant.HOST_URL+"hotInfos.do";
	private final String CAT_INFO_ACTION = Constant.HOST_URL+"catInfos.do";
	private final String PROPUP_CAT_URL = Constant.HOST_URL+"infoCatList.do";
	private String url;
	private static HashMap<String,Integer> infoCatIdPageNumMap = new HashMap<String,Integer>();
	private ListView listView;
	private ListView moreCatListView;
	private String lastCatId;
	private InfoAdapter infoAdapter;
	private SimpleAdapter moreCatAdapter;
	
	private boolean hotInfoFlag = false;
	private Display dispaly;
	private TextView hotInfoText;
	private TextView catInfoText;
	private LinearLayout infoBgLine;
	
	private ImageView triangleImg;
	private int state = 0;//0:最新资讯;1:行业资讯;2:弹出选择行业列表
	private String currentCatInfoName;
	private Resources resources;
	private int width = 0;
	@SuppressWarnings("unused")
	private int height = 0;
	private PopupWindow popupWindow;
	private boolean clickFlag = false;
	private Thread loadInfoListThread;

	private int msgWhat = 0;
	private LinearLayout loadingLayout;
    
	private List<Info> infoList = new ArrayList<Info>();
	
	/**handler用于接收非主线程发送过来的消息并刷新视图界面的UI**/
	private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
        	msgWhat = msg.what;
        	loadingLayout.setVisibility(View.GONE);
            switch (msg.what) {
            	case 0:
            		Toast.makeText(InfoActivity.this, Constant.NO_UPDATE_DATA, Toast.LENGTH_SHORT).show();
            		break;
	            case 1:
	            	@SuppressWarnings("unchecked")
					List<Info> infoLoadList = (List<Info>) msg.obj;
					List<Info> cachInfoList = null;
					if(null != infoLoadList && infoLoadList.size() > 0){
						Info info = infoLoadList.get(0);
						AppCache.infoCatId = info.getCatId()+"";
						cachInfoList = AppCache.catIdInfoListMap.get(AppCache.infoCatId);
						cachInfoList = cachInfoList == null?new ArrayList<Info>():cachInfoList;
						cachInfoList.addAll(infoLoadList);
						AppCache.catIdInfoListMap.put(AppCache.infoCatId, cachInfoList);//保存每个类别对应的资讯列表
						
						Integer pn = infoCatIdPageNumMap.get(AppCache.infoCatId);
						pn = null == pn ?1:pn;
						++pn;
						infoCatIdPageNumMap.put(AppCache.infoCatId, pn);
						
						infoList.clear();
						infoList.addAll(cachInfoList);
						listView.setAdapter(infoAdapter);
						infoAdapter.notifyDataSetChanged();
						Integer select = AppCache.listViewFirstPostionMap.get(AppCache.infoCatId);
						select = null ==select ?0:select;
						listView.setSelection(select);
						
						if(null != currentCatInfoName && !"".equals(currentCatInfoName)){
							catInfoText.setText(currentCatInfoName);
						}
					}
	                break;
	            case 2:
	            	Toast.makeText(InfoActivity.this, Constant.NET_ERROR, Toast.LENGTH_LONG).show();
	            	break;
	            default:
	            	break;
            }
        }
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.info_view);
		resources = this.getResources();
		dispaly = getWindowManager().getDefaultDisplay();
		width = dispaly.getWidth();
		height = dispaly.getHeight();
		
		hotInfoText = (TextView) this.findViewById(R.id.hotInfoText);
		hotInfoText.setWidth(width/2);
		
		catInfoText = (TextView) this.findViewById(R.id.catInfoText);
		triangleImg = (ImageView) this.findViewById(R.id.triangleImg);
		
		infoBgLine = (LinearLayout) this.findViewById(R.id.infoBgline);
		
		listView = (ListView) findViewById(R.id.infoListViewId);
		hotInfoFlag = true;
		loadingLayout = CommonUtil.loadingLayout(InfoActivity.this);//加载数据进度视图布局
		
		infoAdapter = new InfoAdapter(InfoActivity.this, infoList, listView);
		listView.setAdapter(infoAdapter);
		url = HOT_INFO_ACTION;//进入资讯时默认先加载热点资讯列表
		startLoadInfoListThread(url);
		currentCatInfoName = resources.getString(R.string.catInfo);
		listView.setOnScrollListener(new OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){
					int firstVisiblePosition = listView.getFirstVisiblePosition();
					AppCache.listViewFirstPostionMap.put(AppCache.infoCatId, firstVisiblePosition);
				}
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				if(msgWhat != 2 && (firstVisibleItem + visibleItemCount == totalItemCount) && totalItemCount > 0){
					String httpurl = url;
					if(hotInfoFlag)
						httpurl = HOT_INFO_ACTION;
					else 
						httpurl = CAT_INFO_ACTION;
					startLoadInfoListThread(httpurl);
				}
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapter, View view, final int location,long id) {
				Thread t = new Thread(){
					@Override
					public void run() {
						Intent intent = new Intent(InfoActivity.this,BrowseInfoActivity.class);
						Info info = (Info) listView.getItemAtPosition(location);
						String charset = Constant.CHARSET_UTF8;
						info = getInfoWithContentById(info.getId(),charset);
						if(null == info) return;
						intent.putExtra("location", location);
						if(hotInfoFlag){
							intent.putExtra("catInfoName", resources.getString(R.string.hotInfo));
						} else {
							intent.putExtra("catInfoName", catInfoText.getText().toString());
						}
						intent.putExtra("charset", charset);
						intent.putExtra("info", info);
						InfoActivity.this.startActivity(intent);
					}
				};
				t.start();
			}
		});
		
		hotInfoText.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				url = HOT_INFO_ACTION;
				AppCache.infoCatId = null;
				startLoadInfoListThread(url);
				hotInfoFlag = true;
				hotInfoText.setTextColor(Color.rgb(255, 0, 0));
				catInfoText.setTextColor(Color.rgb(0, 0, 0));
				Drawable db = resources.getDrawable(R.drawable.bgline01);
				infoBgLine.setBackgroundDrawable(db);
				state = 0;
				changeTriangleImg();
				/*if(!hotInfoFlag){
					List<Info> cacheList = AppCache.catIdInfoListMap.get(AppCache.infoCatId);
					if(null != cacheList){
						Message msg = new Message();
						msg.obj = cacheList;
						handler.sendMessage(msg);
						hotInfoFlag = true;
					} else {
						
					}
				}*/
			}
		});
		
		catInfoText.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				url = CAT_INFO_ACTION;
				AppCache.infoCatId = lastCatId;
				startLoadInfoListThread(url);
				hotInfoFlag = false;
				hotInfoText.setTextColor(Color.rgb(0, 0, 0));
				catInfoText.setTextColor(Color.rgb(255, 0, 0));
				Drawable db = resources.getDrawable(R.drawable.bgline02);
				infoBgLine.setBackgroundDrawable(db);
				if(0 == state){
					state = 1;
				} else if(1 == state){
					state = 2;
				} else {
					state = 1;
					if(clickFlag)
						state = 2;
				}
				changeTriangleImg();
			}
		});
	}
	
	public static Info getInfoWithContentById(int infoId,String charset){
		String infoUrl = Constant.HOST_URL+"getInfoContentById.do?infoId="+infoId;
		try {
			String content = CommonUtil.getContent(infoUrl,charset,true);
			Info info = new Gson().fromJson(content, new TypeToken<Info>(){}.getType());
			return info;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private void changeTriangleImg() {
		if(2 == state){
			triangleImg.setImageDrawable(resources.getDrawable(R.drawable.up)); 
			if(null == moreCatListView){
				moreCatListView = new ListView(InfoActivity.this);
			}
			//moreCatListView.setId(R.id.propCatListView);
			moreCatAdapter = new SimpleAdapter(this, AppCache.popupCatList, R.layout.more_cat_list, 
					new String[]{INFO_CAT_ID,INFO_CAT_NAME}, new int[]{R.id.cat_id,R.id.moreCatItem});
			moreCatListView.setDivider(resources.getDrawable(R.drawable.line_diver));
			moreCatListView.setDividerHeight(1);
			moreCatListView.setAdapter(moreCatAdapter);
			if(0 == AppCache.popupCatList.size()){
				startLoadPropupCat();//从服务器中下载资讯类别列表
			}
			moreCatListView.setOnItemClickListener(new OnItemClickListener() {
				@SuppressWarnings("unchecked")
				public void onItemClick(AdapterView<?> adapter, View view,int location, long id) {
					if(null != popupWindow) {
						popupWindow.setFocusable(false);
						popupWindow.dismiss();
					}
					HashMap<String,String> slectedMap = (HashMap<String, String>) moreCatListView.getItemAtPosition(location);
					currentCatInfoName = slectedMap.get(INFO_CAT_NAME)+"资讯";
					url = CAT_INFO_ACTION;
					AppCache.infoCatId = slectedMap.get(INFO_CAT_ID);
					lastCatId = AppCache.infoCatId;
					startLoadInfoListThread(url);
					triangleImg.setImageDrawable(resources.getDrawable(R.drawable.down));
					clickFlag = true;
					state = 1;
				}
			});
			
			popupWindow = new PopupWindow(moreCatListView,width/2,LayoutParams.WRAP_CONTENT);
			popupWindow.setBackgroundDrawable(resources.getDrawable(R.drawable.catListBG));
			popupWindow.showAsDropDown(triangleImg, 0, 8);
			popupWindow.setOutsideTouchable(true);
			popupWindow.setFocusable(true);
			popupWindow.update();
		} else {
			if(null != popupWindow) {
				popupWindow.setFocusable(false);
				popupWindow.dismiss();
			}
			clickFlag = false;
			triangleImg.setImageDrawable(resources.getDrawable(R.drawable.down));
		}
	}
	
	/**开启一个新的线程从远程服务器中下载行业资讯信息**/
	private void startLoadPropupCat(){
		new Thread(){
			public void run() {
				int i = 0;
				while(true){
					++i;
					if(i==3){
						break;
					}
					String content = null;
					try {
						content = CommonUtil.getContent(PROPUP_CAT_URL,Constant.CHARSET_GBK,false);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					if(null == content)
						continue;
					List<HashMap<String,String>> dataList = new Gson().fromJson(content, new TypeToken<List<HashMap<String,String>>>(){}.getType());
					if(dataList.size() != 0){
						AppCache.popupCatList.clear();
						AppCache.popupCatList.addAll(dataList);
						moreCatAdapter.notifyDataSetChanged();
						break;
					} else {
						try {
							Thread.sleep(800);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			};
		}.start();
	}
	
	/**开启一个新的线程从远程服务器中下载catId行业类别的资讯列表信息**/
	private void startLoadInfoListThread(String url){
		if(null == loadInfoListThread || !loadInfoListThread.isAlive()){
			loadInfoListThread = new LoadThread(url);
			loadInfoListThread.start();
			loadingLayout.setVisibility(View.VISIBLE);
		}
	}
	
	class LoadThread extends Thread {
		private String url;
		public LoadThread(String url) {
			this.url = url;
		}
		@Override
		public void run() {
			Message msg = new Message();
			String content = null;
			try {
				Integer pn = infoCatIdPageNumMap.get(AppCache.infoCatId);
				pn = null == pn ?1:pn;
				infoCatIdPageNumMap.put(AppCache.infoCatId, pn);
				url += "?pn="+pn;
				url = null == AppCache.infoCatId ? this.url : this.url+"&infoCatId="+ AppCache.infoCatId;
				content = CommonUtil.getContent(url,Constant.CHARSET_GBK,false);
			} catch (IOException e1) {
				e1.printStackTrace();
				msg.what = 2;//2代表网络故障
			}
			if(null != content && !"[]".equals(content.trim())){
				msg.what = 1;//下载资讯列表
				List<Info> infoLoadList = new Gson().fromJson(content, new TypeToken<List<Info>>(){}.getType());
				msg.obj = infoLoadList;
			} else {
				msg.what = 0;//0代表无数据
			}
			handler.sendMessage(msg);
		}
	}
}
